import $mff from './index.js'
/**
 * 基于 Promise 对象实现更简单的 request 使用方式
 */
export default {
  config: {
    baseUrl: '',
    header: {},
    data: {},
    method: "GET",
    dataType: "json",
    responseType: "text",
    success() { },
    fail() { },
    complete() { }
  },
  interceptor: {
    request: null,
    response: null
  },
  request(options) {
    if (!options) {
      options = {}
    }
		this.config.header = {
			'Content-Type': options.contentType ? 'application/x-www-form-urlencoded' : 'application/json'
		}
    options.serverUrl = options.serverUrl || ''
    options.dataType = options.dataType || this.config.dataType
    options.url = options.serverUrl + options.url
    options.data = options.data || {}
    options.method = options.method || this.config.method
    return new Promise((resolve, reject) => {
      let _config = null

      options.complete = (response) => {

        let statusCode = response.statusCode
        response.config = _config

        if (this.interceptor.response) {
          let newResponse = this.interceptor.response(response)
          if (newResponse) {
            response = newResponse
          }
        }
		
        if (statusCode === 200) { //成功
          if (response.data.c == 200) {
						console.log('接口请求成功==>', response.data)
            resolve(response.data)
          } else {
            $mff.wxmethods.toast(response.data.msg)
            reject(response.data);
          }
        } else {
          $mff.wxmethods.toast('请求失败请检查网络')
          reject(response.data)
        }
      }

      _config = Object.assign({}, this.config, options)

      if (this.interceptor.request) {
        this.interceptor.request(_config)
      }
      uni.request(_config);
    });
  },
  get(serverUrl, url, data, options) {
    if (!options) {
      options = {}
    }
    options.serverUrl = serverUrl
    options.url = url
    options.data = data
    options.method = 'GET'
    return this.request(options)
  },
  post(serverUrl, url, data, options) {
    if (!options) {
      options = {}
    }
    options.serverUrl = serverUrl
    options.url = url
    options.data = data
    options.method = 'POST'
    return this.request(options)
  },
  put(serverUrl, url, data, options) {
    if (!options) {
      options = {}
    }
    options.serverUrl = serverUrl
    options.url = url
    options.data = data
    options.method = 'PUT'
    return this.request(options)
  },
  delete(serverUrl, url, data, options) {
    if (!options) {
      options = {}
    }
    options.serverUrl = serverUrl
    options.url = url
    options.data = data
    options.method = 'DELETE'
    return this.request(options)
  }
}